package com.microstation.controller.front;

import com.microstation.common.AppConst;
import com.microstation.common.Assist;
import com.microstation.common.Result;
import com.microstation.controller.system.BaseController;
import com.microstation.entity.po.UserInfo;
import com.microstation.entity.vo.UserInfoVO;
import com.microstation.enums.ResultEnum;
import com.microstation.service.ImgInfoService;
import com.microstation.service.QuestionnaireRecService;
import com.microstation.service.UserInfoService;
import com.microstation.util.CookieUtil;
import com.microstation.util.EnUtil;
import com.microstation.util.MyCookie;
import com.microstation.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.net.URLEncoder;

@RestController
@RequestMapping(value = "/api/userInfo")
public class UserInfoController extends BaseController {

    private final static Logger LOG = LoggerFactory.getLogger(UserInfoController.class);

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private ImgInfoService imgInfoService;
    @Autowired
    private QuestionnaireRecService questionnaireRecService;

    /**
     * 判断登录cookie
     *
     * @param request
     * @return
     */
    @PostMapping(value = "/checkLogin")
    public Result checkLogin(HttpServletRequest request) throws Exception {
        Cookie cookie = CookieUtil.getCookieByName(request, AppConst.COOKIE_NAME);
        if (cookie == null) {
            return new Result(Boolean.TRUE, ResultEnum.NOSESSION, "login.html");
        }
        UserInfoVO userInfoVO = new UserInfoVO();
        userInfoVO.setId(Long.parseLong(CookieUtil.getCookieValByName(request, AppConst.COOKIE_NAME)));
        UserInfo userInfo = userInfoService.getByExample(userInfoVO);
        Assist assist = new Assist();
        assist.andEq("user_id", userInfo.getId());
        assist.andEq("act_id", userInfo.getActId());
        assist.andEq("del_flag", 1);
        userInfo.setQuesStatus(questionnaireRecService.getQuestionnaireRecRowCount(assist).longValue() > 0L ? 1 : 0);
        return new Result(Boolean.FALSE, ResultEnum.SUCCESS, userInfo, "index.html");
    }

    /**
     * 登录
     *
     * @param regNumber
     * @param mobile
     * @param response
     * @return
     */
    @RequestMapping(value = "/login")
    public Result login(String inviteCode, String regNumber, String mobile, HttpServletResponse response) {
        MyCookie cookie = null;
        try {
            //if (StringUtil.isEmpty(regNumber)) {
            //    return new Result(Boolean.TRUE, ResultEnum.EMPTY.getType(), "请输入报名号", AppConst.NULL);
            //}
            //if (StringUtil.isEmpty(mobile)) {
            //    return new Result(Boolean.TRUE, ResultEnum.EMPTY.getType(), "请输入手机号", AppConst.NULL);
            //}
            if (StringUtil.isEmpty(inviteCode)) {
                return new Result(Boolean.TRUE, ResultEnum.EMPTY.getType(), "请输入邀请码", AppConst.NULL);
            }
            UserInfoVO userInfoVO = new UserInfoVO();
            userInfoVO.setInviteCode(inviteCode);
            userInfoVO.setDelFlag(1);
            UserInfo userInfo = userInfoService.getByExample(userInfoVO);
            if (userInfo == null) {
                return new Result(Boolean.TRUE, ResultEnum.NORECORD, AppConst.NULL);
            }
            cookie = new MyCookie(AppConst.COOKIE_NAME, String.valueOf(userInfo.getId()));
            // 设置Cookie的有效期为7天
            cookie.setMaxAge(7 * 24 * 60 * 60);
            // 设置路径，这个路径即该工程下都可以访问该cookie
            // 如果不设置路径，那么只有设置该cookie路径及其子路径可以访问
            cookie.setPath("/");
            CookieUtil.addCookie(response, cookie, Boolean.TRUE);
            return new Result(Boolean.FALSE, ResultEnum.SUCCESS, userInfo, AppConst.NULL);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Boolean.TRUE, ResultEnum.ERROR.getType(), e.getMessage(), AppConst.NULL);
        }
    }

    @RequestMapping(value = "/loginOut")
    public Result loginOut(HttpServletResponse response) {
        Cookie cookie = new Cookie(AppConst.COOKIE_NAME, AppConst.NULL);
        // 设置Cookie的有效期为7天
        cookie.setMaxAge(0);
        // 设置路径，这个路径即该工程下都可以访问该cookie
        // 如果不设置路径，那么只有设置该cookie路径及其子路径可以访问
        cookie.setPath("/");
        CookieUtil.addCookie(response, cookie, Boolean.TRUE);
        return new Result(Boolean.FALSE, ResultEnum.SUCCESS, "login.html");
    }

    /**
     * 获取用户注册信息
     *
     * @param request
     * @return
     */
    @PostMapping(value = "/getUserInfo")
    public Result getUserInfo(HttpServletRequest request) {
        try {
            UserInfoVO userInfoVO = new UserInfoVO();
            userInfoVO.setId(Long.parseLong(CookieUtil.getCookieValByName(request, AppConst.COOKIE_NAME)));
            UserInfo userInfo = userInfoService.getByExample(userInfoVO);
            return new Result(Boolean.FALSE, ResultEnum.SUCCESS, userInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Boolean.TRUE, ResultEnum.ERROR.getType(), e.getMessage(), AppConst.NULL);
        }
    }

    /**
     * 保存用户
     *
     * @param userInfoVO
     * @param request
     * @return
     */
    @RequestMapping(value = "/saveUserInfo")
    public Result saveUserInfo(UserInfoVO userInfoVO, HttpServletRequest request) {
        try {
            userInfoVO.setId(Long.parseLong(CookieUtil.getCookieValByName(request, AppConst.COOKIE_NAME)));
            Integer res = userInfoService.updateNotNullById(userInfoVO);
            if (res != null && res.intValue() != 0) {
                return new Result(Boolean.FALSE, ResultEnum.SUCCESS, AppConst.NULL);
            }
            return new Result(Boolean.TRUE, ResultEnum.FALSE, userInfoService.findOne(userInfoVO.getId()), AppConst.NULL);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Boolean.TRUE, ResultEnum.ERROR.getType(), e.getMessage(), AppConst.NULL);
        }
    }

    /**
     * 确认保存
     *
     * @return
     */
    @PostMapping(value = "/comfirmSaveInfo")
    public Result comfirmSaveInfo(HttpServletRequest request) {
        Result result = new Result();
        UserInfo userInfo = new UserInfo();
        try {
            userInfo.setId(Long.parseLong(CookieUtil.getCookieValByName(request, AppConst.COOKIE_NAME)));
            userInfo.setRegFlag(1);
            Integer res = userInfoService.updateNotNullById(userInfo);
            if (res.intValue() != 0) {
                return new Result(Boolean.FALSE, ResultEnum.SUCCESS, AppConst.NULL);
            } else {
                return new Result(Boolean.TRUE, ResultEnum.ERROR.getType(), "已提交", AppConst.NULL);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Boolean.TRUE, ResultEnum.ERROR.getType(), e.getMessage(), AppConst.NULL);
        }
    }

    /**
     * 大会相册
     *
     * @return
     */
    @PostMapping(value = "/loadImgList")
    public Result loadImgList() {
        Result result = new Result();
        Assist assist = new Assist();
        assist.andEq("del_flag", 1);
        assist.setOrder(Assist.order("id", false));
        result = imgInfoService.find(assist);
        return result;
    }

    /**
     * 我的二维码
     *
     * @param request
     * @return
     */
    @PostMapping(value = "getMyQRCode")
    public Result getMyQRCode(HttpServletRequest request) {
        try {
            String filePath = request.getSession().getServletContext().getRealPath("/upload");
            return userInfoService.updateQrcode(Long.parseLong(CookieUtil.getCookieValByName(request, AppConst.COOKIE_NAME)), filePath);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Boolean.TRUE, ResultEnum.ERROR.getType(), e.getMessage(), AppConst.NULL);
        }
    }
}
